package com.sjq.common.web.api;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sjq.common.entity.ErrorJson;
import com.sjq.common.entity.LoginAccount;
import com.sjq.common.entity.LoginLog;
import com.sjq.common.entity.User;
import com.sjq.common.service.LoginLogService;
import com.sjq.common.service.LoginService;
import com.sjq.common.web.SessionUserHelper;


@RestController
@RequestMapping(value = "/api/v1/security")
public class LoginRestController {

    private static final Logger LOG = LoggerFactory.getLogger(LoginRestController.class);
    private static final String MAIN_URL = "/main/mh";

    @Autowired
    private LoginService loginService;
    @Resource
    private LoginLogService lls;
    
    @RequestMapping(value = "/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpServletRequest request) {
        User user = loginService.checkLogin(username, password);
        saveAccountToSession(request, user);
        JSONObject jsonResult = createJsonResultAndSaveToSession(request, user);
      //  LOG.debug("result =" + jsonResult.toString());
        return jsonResult.toString();
    }

    
    @RequestMapping("/check-login")
    public String checkLogin(HttpServletRequest req){
    	SessionUserHelper helper = SessionUserHelper.create(req);
    	if(helper.checkLoginSuccess()){
    		return "success";
    	}
    	return "error";
    }

    @RequestMapping("/pkiLogin")
    public String pkiLogin(HttpServletRequest req){
    	String gmsfhm=req.getParameter("gmsfhm");
    	 User user = loginService.checkPkiLogin(gmsfhm);
    	 saveAccountToSession(req, user);
    	 JSONObject jsonResult = createJsonResultAndSaveToSession(req, user);
         return jsonResult.toString();
    }
    private void saveAccountToSession(HttpServletRequest request, User user) {
        if (user == null) {
            return;
        }
        LoginAccount account = new LoginAccount(user.getJH(), user.getYHM(),
                user.getXM(),user.getROLEDM(),user.getDWBM(),user.getDWMC(),user.getUserIp(),user.getLXFS());
        account.setUserIp(getMyIp(request));
        SessionUserHelper helper = SessionUserHelper.create(request);
        helper.saveToSession(account);
    }

    private JSONObject createJsonResultAndSaveToSession(HttpServletRequest request, User user) {
        JSONObject jsonResult = new JSONObject();

        if (user == null) {
            jsonResult.put("status", 1);
            jsonResult.put("error", new ErrorJson("001", "您输入的账号或密码有误"));
            return jsonResult;
        }
       
        //存储登录日志
        LoginLog tsd = new LoginLog();
        tsd.setYHM(user.getYHM());
        tsd.setGAJGJGDM(user.getDWBM());
        tsd.setIPDZ(getMyIp(request));
        
        Map<String,String> map = lls.insertLoginLog(tsd);
        
        
        String forwardUrl = String.format("%s%s", request.getContextPath(), MAIN_URL);
        jsonResult.put("status", 0);
        HashMap<String, String> dataValue = new HashMap<String, String>();
        dataValue.put("forward_url", forwardUrl);
        jsonResult.put("data", dataValue);

        return jsonResult;
    }
    
    
    
    public String getMyIp(HttpServletRequest request){
    	//获取登录用户ip
        String ip = request.getHeader("x-forwarded-for");
        if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
        	ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
        	ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
        	ip = request.getRemoteAddr();
        }
		return ip;
    }
    
    
}

